﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace _6.EmailExtraction
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "My Email addres.aakl is kristinalkoeva@gmail.com.bg, kristina-l@ko.k.com " +
                "kri.@. krio@bg";

            List<string> samples = new List<string>();
            samples.Add("joe");
            samples.Add("joe@home");
            samples.Add("a@b.c");
            samples.Add("joe@home.com");
            samples.Add("joe.bob@home.com");
            samples.Add("joe-bob[at]home.com");
            samples.Add("joe@his.home.com");
            samples.Add("joe@his.home.place");
            samples.Add("joe@home.org");
            samples.Add("joe@joebob.name");
            samples.Add("joe.@bob.com");
            samples.Add(".joe@bob.com");
            samples.Add("joe<>bob@bob.come");
            samples.Add("joe&bob@bob.com");
            samples.Add("~joe@bob.com");
            samples.Add("joe$@bob.com");
            samples.Add("joe+bob@bob.com");
            samples.Add("o'reilly@there.com");
            samples.Add("reilly@there.com, pesho@musaka.kyfte.mente.bg");

            foreach (string email in samples)
            {
                ExtractEmails(email);
            }
        }

        public static void ExtractEmails(string inputText)
        {
            //<identifier>@<host>…<domain>
            string identifierPattern = @"([a-zA-Z]+(\.\w+)*)";
            string hostAndDomainPattern = @"[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*(\.\w{2,4})";

            Regex regex = new Regex(@"(\A|[ ,;])(" + identifierPattern + "@" + hostAndDomainPattern + @")(\Z|[ ,;])", 
                RegexOptions.IgnoreCase);

            MatchCollection matches = regex.Matches(inputText);

            foreach (Match match in matches)
            {
                Console.WriteLine(match.Groups[2] + " at " + match.Index);
            }
        }
    }
}
